<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Video Downloader</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .progress-bar {
            transition: width 0.3s ease-in-out;
            background: linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%);
            background-size: 200% 100%;
            animation: gradient 2s linear infinite;
        }

        @keyframes gradient {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .loading-dots:after {
            content: '.';
            animation: dots 1.5s steps(5, end) infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60% { content: '...'; }
            80%, 100% { content: ''; }
        }

        .pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: .7; }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <header class="text-center mb-12">
            <h1 class="text-4xl font-bold text-gray-800 mb-4">YouTube Video Downloader</h1>
            <p class="text-gray-600">Download and manage your favorite YouTube videos</p>
        </header>

        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <div id="urlInputs" class="space-y-4 mb-4">
                <div class="flex flex-col md:flex-row gap-4">
                    <input type="text" 
                        class="url-input flex-1 px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                        placeholder="Enter YouTube URL">
                    <button onclick="removeUrlInput(this)" 
                        class="text-red-500 px-4 py-2 rounded-lg hover:bg-red-50 transition-colors duration-200">
                        Remove
                    </button>
                </div>
            </div>
            
            <div class="flex justify-between mb-4">
                <button onclick="addUrlInput()" 
                    class="text-blue-500 px-4 py-2 rounded-lg hover:bg-blue-50 transition-colors duration-200">
                    + Add Another URL
                </button>
                <button onclick="startBatchDownload()" 
                    class="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition-colors duration-200">
                    Download All
                </button>
            </div>

            <div id="batchProgress" class="space-y-4">
                <!-- Progress bars will be added here dynamically -->
            </div>
        </div>

        <div class="bg-white rounded-lg shadow-lg p-6">
            <h2 class="text-2xl font-semibold mb-4">Downloaded Videos</h2>
            <div id="videosList" class="space-y-4">
                {% for video in videos %}
                <div class="border rounded-lg p-4 hover:bg-gray-50">
                    <div class="flex flex-col md:flex-row gap-4">
                        <div class="md:w-1/3">
                            <video controls class="w-full rounded-lg">
                                <source src="{{ url_for('serve_video', filename=video.filename) }}" type="video/mp4">
                                Your browser does not support the video tag.
                            </video>
                        </div>
                        <div class="flex-1">
                            <h3 class="text-xl font-semibold mb-2">{{ video.title }}</h3>
                            <p class="text-gray-600 mb-2">
                                <span class="font-medium">Duration:</span> {{ video.duration // 60 }}:{{ video.duration % 60 }}
                            </p>
                            <p class="text-gray-600 mb-2">
                                <span class="font-medium">Uploader:</span> {{ video.uploader }}
                            </p>
                            <p class="text-gray-600 mb-2">
                                <span class="font-medium">File Size:</span> {{ video.file_size }}
                            </p>
                            <p class="text-gray-600 mb-2">
                                <span class="font-medium">Path:</span> {{ video.file_path }}
                            </p>
                            <p class="text-gray-600 text-sm line-clamp-3">{{ video.description }}</p>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>

    <script>
        function addUrlInput() {
            const template = `
                <div class="flex flex-col md:flex-row gap-4">
                    <input type="text" 
                        class="url-input flex-1 px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                        placeholder="Enter YouTube URL">
                    <button onclick="removeUrlInput(this)" 
                        class="text-red-500 px-4 py-2 rounded-lg hover:bg-red-50 transition-colors duration-200">
                        Remove
                    </button>
                </div>
            `;
            document.getElementById('urlInputs').insertAdjacentHTML('beforeend', template);
        }

        function removeUrlInput(button) {
            button.parentElement.remove();
        }

        function createProgressBar(url, index) {
            const progressId = `progress-${index}`;
            const template = `
                <div id="${progressId}" class="border rounded-lg p-4">
                    <div class="text-sm font-medium mb-2 truncate">${url}</div>
                    <div class="relative pt-1">
                        <div class="flex mb-2 items-center justify-between">
                            <div>
                                <span class="progress-status text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-blue-600 bg-blue-200">
                                    Waiting<span class="loading-dots"></span>
                                </span>
                            </div>
                            <div class="text-right">
                                <span class="progress-percent text-xs font-semibold inline-block text-blue-600">
                                    0%
                                </span>
                            </div>
                        </div>
                        <div class="overflow-hidden h-2 mb-4 text-xs flex rounded bg-blue-100">
                            <div class="progress-bar shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center" 
                                 style="width: 0%">
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-4 text-xs text-gray-600">
                            <div class="download-speed pulse">Speed: 0 MB/s</div>
                            <div class="time-remaining text-right pulse">Time remaining: calculating...</div>
                            <div class="downloaded-size pulse">Downloaded: 0 MB</div>
                            <div class="total-size text-right pulse">Total size: calculating...</div>
                        </div>
                    </div>
                </div>
            `;
            document.getElementById('batchProgress').insertAdjacentHTML('beforeend', template);
            return progressId;
        }

        async function startBatchDownload() {
            const urls = Array.from(document.getElementsByClassName('url-input'))
                .map(input => input.value.trim())
                .filter(url => url);

            if (urls.length === 0) {
                alert('Please enter at least one URL');
                return;
            }

            document.getElementById('batchProgress').innerHTML = '';
            
            for (let i = 0; i < urls.length; i++) {
                const url = urls[i];
                const progressId = createProgressBar(url, i);
                
                try {
                    const response = await fetch('/download', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ url }),
                    });

                    if (!response.ok) {
                        throw new Error('Download failed');
                    }

                    const { video_id } = await response.json();
                    monitorProgress(video_id, progressId);
                } catch (error) {
                    const progressElement = document.getElementById(progressId);
                    const progressStatus = progressElement.querySelector('.progress-status');
                    progressStatus.textContent = 'Error: ' + error.message;
                    progressStatus.classList.remove('text-blue-600', 'bg-blue-200');
                    progressStatus.classList.add('text-red-600', 'bg-red-200');
                }
            }
        }

        async function monitorProgress(videoId, progressId) {
            const progressElement = document.getElementById(progressId);
            const progressBar = progressElement.querySelector('.progress-bar');
            const progressStatus = progressElement.querySelector('.progress-status');
            const progressPercent = progressElement.querySelector('.progress-percent');
            const downloadSpeed = progressElement.querySelector('.download-speed');
            const timeRemaining = progressElement.querySelector('.time-remaining');
            const downloadedSize = progressElement.querySelector('.downloaded-size');
            const totalSize = progressElement.querySelector('.total-size');

            while (true) {
                try {
                    const response = await fetch(`/progress/${videoId}`);
                    const progress = await response.json();

                    if (progress.status === 'downloading') {
                        const percent = (progress.downloaded_bytes / progress.total_bytes * 100) || 0;
                        progressBar.style.width = `${percent}%`;
                        progressPercent.textContent = `${percent.toFixed(1)}%`;
                        
                        const speed = (progress.speed / 1024 / 1024).toFixed(2);
                        const downloaded = (progress.downloaded_bytes / 1024 / 1024).toFixed(1);
                        const total = (progress.total_bytes / 1024 / 1024).toFixed(1);
                        const remaining = ((progress.total_bytes - progress.downloaded_bytes) / progress.speed);
                        
                        progressStatus.innerHTML = 'Downloading<span class="loading-dots"></span>';
                        downloadSpeed.textContent = `Speed: ${speed} MB/s`;
                        downloadedSize.textContent = `Downloaded: ${downloaded} MB`;
                        totalSize.textContent = `Total size: ${total} MB`;
                        timeRemaining.textContent = `Time remaining: ${formatTime(remaining)}`;
                    } else if (progress.status === 'completed') {
                        progressBar.style.width = '100%';
                        progressStatus.textContent = 'Completed!';
                        progressStatus.classList.remove('text-blue-600', 'bg-blue-200');
                        progressStatus.classList.add('text-green-600', 'bg-green-200');
                        progressPercent.textContent = '100%';
                        
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                        break;
                    } else if (progress.status === 'error') {
                        progressStatus.textContent = 'Error: ' + progress.error;
                        progressStatus.classList.remove('text-blue-600', 'bg-blue-200');
                        progressStatus.classList.add('text-red-600', 'bg-red-200');
                        break;
                    }
                } catch (error) {
                    progressStatus.textContent = 'Error checking progress';
                    progressStatus.classList.remove('text-blue-600', 'bg-blue-200');
                    progressStatus.classList.add('text-red-600', 'bg-red-200');
                    break;
                }
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
        }

        function formatTime(seconds) {
            if (!seconds || seconds === Infinity) return 'calculating...';
            
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            seconds = Math.floor(seconds % 60);
            
            const parts = [];
            if (hours > 0) parts.push(`${hours}h`);
            if (minutes > 0) parts.push(`${minutes}m`);
            if (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);
            
            return parts.join(' ');
        }
    </script>
</body>
</html> 